package com.rankeiot.developer.controller;

import com.rankeiot.core.util.StringUtil;
import com.rankeiot.developer.component.service.ComponentMagicDynamicRegistry;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.rankeiot.developer.component.model.ComponentInfo;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import java.util.Locale;


@Controller
@RequiredArgsConstructor
public class PageController {

    private final ComponentMagicDynamicRegistry registry;

    private final MediaType TEXT_JAVASCRIPT = MediaType.parseMediaType("text/javascript");

    private final static DateTimeFormatter DATE_FORMATTER;
    private final static ZoneId GMT;

    private static String formatDate(long date) {
        Instant instant = Instant.ofEpochMilli(date);
        ZonedDateTime time = ZonedDateTime.ofInstant(instant, GMT);
        return DATE_FORMATTER.format(time);
    }

    static {
        GMT = ZoneId.of("GMT");
        DATE_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).withZone(GMT);
    }

    @GetMapping("/page/**")
    public ResponseEntity getPage(HttpServletRequest req,String source) {
        String uri = req.getRequestURI();
        int i = uri.indexOf("/page/") + 5;
        String path = uri.substring(i);
        if(path.endsWith(".js")){
            path=path.substring(0,path.length()-2)+"vue";
        }
        if (!path.endsWith(".vue")) {
            return ResponseEntity.status(404).build();
        }
        ComponentInfo componentInfo = registry.getMapping(path);
        if (componentInfo == null) {
            return ResponseEntity.status(404).build();
        }
        String md = req.getHeader("If-Modified-Since");
        Long updateTime = componentInfo.getUpdateTime();
        if (updateTime == null) {
            updateTime = componentInfo.getCreateTime();
        }
        if (StringUtil.isNotEmpty(md)) {
            String realDate = formatDate(updateTime);
            if (md.equals(realDate)) {
                return ResponseEntity.status(304).build();
            }
        }
        //If-Modified-Since
        //Sec-Fetch-Mode
        //页面请求
        /**
         if ("document".equals(req.getHeader("Sec-Fetch-Dest"))) {
         String basePath=uri.substring(0,i-4);
         Template template = engine.getTemplate("/page.html");
         Map<String, Object> params = new HashMap<>();
         params.put("config", Config.configMap());
         params.put("basePath",basePath);
         params.put("source",componentInfo.getCompiledScript().replaceFirst("export default","const _page="));
         params.put("path",path.replaceFirst("\\.html$",".vue"));
         return ResponseEntity.status(200)
         .lastModified(updateTime)
         .contentType(MediaType.TEXT_HTML)
         .body(template.renderToString(params));
         }**/
        if(source!=null&&"debug.vue".equals(source)){
            return ResponseEntity.status(200)
                    .lastModified(updateTime)
                    .contentType(MediaType.TEXT_HTML)
                    .body(componentInfo.getScript());
        }else{
            return ResponseEntity.status(200)
                    .lastModified(updateTime)
                    .contentType(TEXT_JAVASCRIPT)
                    .body(componentInfo.getCompiledScript());
        }

    }
}
